﻿/************************************************************************
* Copyright (c) 2018 All Rights Reserved.
*命名空间：SERVICE.Admin.Service
*文件名： SyetemService
*创建人： kingling
*创建时间：2018/7/6 15:29:12
*描述
*=======================================================================
*修改标记
*修改时间：2018/7/6 15:29:12
*修改人：kingling
*描述：
************************************************************************/

using CacheService.Standard;
using Common.Standard;
using DAL.IDal;
using MODEL.Model;
using SERVICE.Admin.IService;
using System;
using System.Collections.Generic;
using System.Linq;

namespace SERVICE.Admin.Service
{
    public class SyetemService : ISyetemService
    {
        ISystemManagerDal managerDal;
        ISystemRuleDal systemRuleDal;
        ISystemMenuDal menuDal;
        ICache cache;

        public SyetemService(ISystemManagerDal managerDal, ISystemRuleDal systemRuleDal, ICache cache, ISystemMenuDal menuDal)
        {
            this.managerDal = managerDal;
            this.systemRuleDal = systemRuleDal;
            this.cache = cache;
            this.menuDal = menuDal;
        }

        SystemManager ISyetemService.AddManager(SystemManager manager)
        {
            if (string.IsNullOrWhiteSpace(manager.loginName) || string.IsNullOrWhiteSpace(manager.userName) || string.IsNullOrWhiteSpace(manager.mobile) || string.IsNullOrWhiteSpace(manager.pass))
            {
                throw new Error("参数不能为空");
            }
            //账号查重
            var hasAccont = managerDal.Query(x => x.loginName == manager.loginName || x.mobile == manager.mobile).Any();
            if (hasAccont)
            {
                throw new Error("用户已经存在");
            }
            //权限查询
            var rule = systemRuleDal.Query(x => x.id == manager.rid).FirstOrDefault();
            if (rule == null)
            {
                throw new Error("角色不存在");
            }
            manager.pass = StringEncyptionHelper.Md5(manager.pass);
            if (managerDal.Add(manager))
            {
                return manager;
            }
            throw new Error("添加失败");
        }

        bool ISyetemService.AddRule(string name, IList<string> actionNames)
        {
            if (actionNames.Count == 0)
            {
                throw new Error("该角色没有选择任何权限");
            }
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new Error("名称不能为空");
            }
            //名称查重
            var hasName = systemRuleDal.Query(x => x.name == name.Trim()).Any();
            if (hasName)
            {
                throw new Error("角色名已经存在");
            }
            var rule = new SystemRule
            {
                name = name,
                SystemJurisdictions = new List<SystemJurisdiction>(),
            };
            foreach (string path in actionNames.Distinct())
            {
                var jur = new SystemJurisdiction
                {
                    name = path
                };
                rule.SystemJurisdictions.Add(jur);
            }
            return systemRuleDal.Add(rule);
        }

        bool ISyetemService.DelManager(int id)
        {
            var user = managerDal.Query(x => x.id == id).FirstOrDefault();
            if (user == null)
            {
                throw new Error("管理员不存在");
            }
            user.del = true;
            return managerDal.Update(user);
        }

        bool ISyetemService.DelRule(int id)
        {
            var use = managerDal.Query(x => x.rid == id).Any();
            if (use)
            {
                throw new Error("不能删除该角色,因为有人正在使用");
            }
            var rule = systemRuleDal.Query(x => x.id == id).FirstOrDefault();
            if (rule == null)
            {
                throw new Error("角色不存在");
            }
            rule.del = true;
            return systemRuleDal.Update(rule);
        }

        SystemManager ISyetemService.GetLoginManger(string key)
        {
            return cache.get<SystemManager>(key);
        }

        IList<SystemManager> ISyetemService.GetManagers(int page, out int total, out int pageSize)
        {
            return managerDal.QueryByPage(x => x.id > 0, x => x.id, out total, out pageSize, page, IsAsc: false, includes: x => x.SystemRule).ToList();
        }

        List<SystemMenu> ISyetemService.GetMenu()
        {
            var list = cache.get<List<SystemMenu>>("menus");
            if (list == null)
            {
                list = menuDal.Query(x => x.id > 0, x => x.SystemMenuPaths).OrderBy(x => x.sort).ToList();
                cache.setWithLasting("menus", list);
            }
            return list;
        }

        SystemRule ISyetemService.GetRule(int id)
        {
            var rule = systemRuleDal.Query(x => x.id == id, x => x.SystemJurisdictions).FirstOrDefault();
            return rule == null ? throw new Error("角色不存在") : rule;
        }

        IList<SystemRule> ISyetemService.GetRules()
        {
            return systemRuleDal.Query(x => x.id > 0, x => x.SystemJurisdictions).ToList();
        }

        bool ISyetemService.MdyRule(int id, string name, IList<string> actionNames)
        {
            if (actionNames.Count == 0)
            {
                throw new Error("该角色没有选择任何权限");
            }
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new Error("名称不能为空");
            }
            var rule = systemRuleDal.Query(x => x.id == id, x => x.SystemJurisdictions).FirstOrDefault();
            if (rule == null)
            {
                throw new Error("角色不存在");
            }
            rule.name = name;
            rule.SystemJurisdictions.Clear();
            foreach (string path in actionNames.Distinct())
            {
                var jur = new SystemJurisdiction
                {
                    name = path
                };
                rule.SystemJurisdictions.Add(jur);
            }
            return systemRuleDal.Update(rule);
        }

        SystemManager ISyetemService.OnLogin(string loginName, string pass)
        {
            var p = StringEncyptionHelper.Md5(pass);
            var user = managerDal.Query(x => x.loginName == loginName && x.pass == p).FirstOrDefault();
            if (user == null)
            {
                throw new Error("用户不存在");
            }
            var rule = systemRuleDal.Query(x => x.id == user.rid, x => x.SystemJurisdictions).FirstOrDefault();
            return user;
        }

        bool ISyetemService.SaveMenu(IList<SystemMenu> systemMenus)
        {
            var menus = menuDal.Query(x => x.id > 0).ToList();
            menuDal.Delete(menus, false);
            cache.delete("menus");
            return menuDal.Add(systemMenus);
        }

        SystemManager ISyetemService.UpdateManager(SystemManager manager)
        {
            if (string.IsNullOrWhiteSpace(manager.loginName) || string.IsNullOrWhiteSpace(manager.userName) || string.IsNullOrWhiteSpace(manager.mobile))
            {
                throw new Error("参数不能为空");
            }
            var user = managerDal.Query(x => x.id == manager.id).FirstOrDefault();
            if (user == null)
            {
                throw new Error("用户不存在");
            }

            //账号查重
            var hasAccont = managerDal.Query(x => (x.loginName == manager.loginName || x.mobile == manager.mobile) && x.id != manager.id).Any();
            if (hasAccont)
            {
                throw new Error("用户已经存在");
            }
            user.loginName = manager.loginName;
            user.userName = manager.userName;
            user.mobile = manager.mobile;
            user.rid = manager.rid;
            if (!string.IsNullOrWhiteSpace(manager.pass))
            {
                user.pass = StringEncyptionHelper.Md5(manager.pass);
            }
            //权限查询
            var rule = systemRuleDal.Query(x => x.id == user.rid).FirstOrDefault();
            if (rule == null)
            {
                throw new Error("角色不存在");
            }
            if (managerDal.Update(user))
            {
                return user;
            }
            throw new Error("管理员修改失败");
        }

        bool ISyetemService.UpdatePass(int id, string oldPass, string newPass)
        {
            if (string.IsNullOrWhiteSpace(newPass))
            {
                throw new Error("密码不能为空");
            }
            var user = managerDal.Query(x => x.id == id).FirstOrDefault();
            if (user == null)
            {
                throw new Error("用户不存在");
            }
            if (user.pass != StringEncyptionHelper.Md5(oldPass))
            {
                throw new Error("原密码错误");
            }
            user.pass = StringEncyptionHelper.Md5(newPass);
            return managerDal.Update(user);
        }

        void ISyetemService.InitData()
        {
            //菜单
            if (menuDal.Count(x => x.id > 0) == 0)
            {
                var systemMenus = new List<SystemMenu>();
                var menu = new SystemMenu
                {
                    name = "系统设置",
                    sort = 9,
                    icon = "fa-cog"
                };
                menu.SystemMenuPaths.Add(new SystemMenuPath
                {
                    name = "添加角色",
                    path = "/AddRule/Index"
                });
                menu.SystemMenuPaths.Add(new SystemMenuPath
                {
                    name = "管理员管理",
                    path = "/Master/Index"
                });
                menu.SystemMenuPaths.Add(new SystemMenuPath
                {
                    name = "菜单设置",
                    path = "/Menu/Index"
                });
                menu.SystemMenuPaths.Add(new SystemMenuPath
                {
                    name = "角色列表",
                    path = "/Rule/Index"
                });
                systemMenus.Add(menu);
                menuDal.Add(systemMenus);
            }
            //权限
            if (systemRuleDal.Count(x => x.id > 0) == 0)
            {
                var rule = new SystemRule
                {
                    name = "初始管理员",
                    SystemJurisdictions = new List<SystemJurisdiction>()
                };
                rule.SystemJurisdictions.Add(new SystemJurisdiction
                {
                    name = "添加角色"
                });
                rule.SystemJurisdictions.Add(new SystemJurisdiction
                {
                    name = "管理员管理"
                });
                rule.SystemJurisdictions.Add(new SystemJurisdiction
                {
                    name = "菜单设置"
                });
                rule.SystemJurisdictions.Add(new SystemJurisdiction
                {
                    name = "角色列表"
                });
                rule.SystemJurisdictions.Add(new SystemJurisdiction
                {
                    name = "修改角色"
                });
                rule.SystemJurisdictions.Add(new SystemJurisdiction
                {
                    name = "添加/修改管理员"
                });
                var user = new SystemManager
                {
                    loginName = "admin",
                    pass = StringEncyptionHelper.Md5("admin"),
                    SystemRule = rule,
                    userName = "恩鼎科技"
                };
                managerDal.Add(user);
            }
        }
    }
}
